package EBM.DB;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import EBM.model.Model;

public class ProjectModelDAO {
	private List<Object> response;
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;
	private String sql;
	private int result;

	public ProjectModelDAO(){
		response = null;
		conn = null;
		ps = null;
		rs = null;
		sql = null;
		result = 0;
	}

	public boolean save(Object name, Object proid) 
	throws SQLException, ClassNotFoundException{

		if (name == null || proid == null)
			return false;
		
		String sql="insert into project_model(name,proid) values(?,?)";

		conn = DBConnection.getConn();
		ps = conn.prepareStatement(sql);

		response = new ArrayList<Object>();

		ps.setObject(1, name);
		ps.setObject(2, proid);

		result = ps.executeUpdate();
		conn.close();

		if(result>0){
			return true;
		}else{
			return false;
		}
	}

	public boolean delete(String sub_name, int id, String proid) 
	throws SQLException, ClassNotFoundException{

		String sql1 = "select * from bug_" + proid + " where bug_model  = ?";
		String sql2 = "delete from project_model where name=? and proid = ?";

		response = new ArrayList<Object>();
		conn = DBConnection.getConn();
		ps = conn.prepareStatement(sql1);
		ps.setObject(1, sub_name);
		rs = ps.executeQuery();
		if (rs.next())
			return false;

		ps = conn.prepareStatement(sql2);
		ps.setObject(1, sub_name);
		ps.setInt(2, id);

		result = ps.executeUpdate();
		conn.close();

		if(result>0){
			return true;
		}else{
			return false;
		}
	}

	public List<Object> findByProid(Object proId) 
	throws SQLException, ClassNotFoundException{

		sql="select * from project_model where proid=?";

		conn = DBConnection.getConn();
		ps = conn.prepareStatement(sql);

		ps.setObject(1, proId);

		rs=ps.executeQuery();

		response = new ArrayList<Object>();
		if(rs.next()){
			do{
				Model m = new Model();
				m.setName(rs.getString("name"));
				m.setId(String.valueOf(rs.getInt("id")));
				m.setProid(rs.getString("proid"));
				response.add(m);
			}while(rs.next());
		}
		conn.close();

		return response;
	}

	public List<Object> findByNameAndProid(Object name, Object proId) 
	throws SQLException, ClassNotFoundException{

		sql="select * from project_model where name=? and proid=?";

		conn = DBConnection.getConn();
		ps = conn.prepareStatement(sql);

		ps.setObject(1, name);
		ps.setObject(2, proId);

		rs=ps.executeQuery();

		response = new ArrayList<Object>();
		if(rs.next()){
			response.add(rs.getObject("id"));
		}
		conn.close();

		return response;
	}


}
